package nz.co.album.converse.connector;

import java.io.IOException;
import java.net.UnknownHostException;

import ie.omk.smpp.*;
import ie.omk.smpp.message.*;

public class SMSConnector {

	private Connection connection;
	
	public void sendSMS(String destination, String message) {
		try {
			connection = new Connection("", 2775, true);
		} catch(UnknownHostException e) {
			throw new RuntimeException("Error connecting to SMSC", e);
		}
		
		boolean bound = false;
		while(!bound) {
			try {
				connection.bind(Connection.TRANSCEIVER, "sysId", "secret", null);
				bound = true;
			} catch(IOException e) {
				// TODO: log this or something
				try {
					Thread.sleep(60 * 1000);
				} catch(InterruptedException ex) {}
			}
		}
		
		SMPPPacket sms;
		
		try {
			sms = connection.newInstance(SMPPPacket.SUBMIT_SM);
		} catch(BadCommandIDException e) {
			throw new RuntimeException("Error creating new SMS", e);
		}
		
		Address address = new Address();
		address.setAddress(destination);
		sms.setDestination(address);
		
		sms.setMessageText(message);
		
		try {
			connection.sendRequest((SMPPRequest) sms);
		} catch(IOException e) {
			throw new RuntimeException("Error sending SMS", e);
		}
	}

}
